<template>
	<!-- 选择模版组件 -->
	<view class="container" @click="fabCloseClick">
		<u-popup :show="show" mode="left" @close="close" @open="open" style="width:100%">

			<view class="scrollContent" style="" @click="fabCloseClick">
				<text class="title" style="font-size: 13px;">封皮模版</text>
				<!-- 滑动区域 -->
				<view class="" style="display: flex;height: 240px;">
					<view v-if="favList.length!==0" class="top_scrollx" style="width: 60%;">
						<scroll-view class="uni-swiper-tab" scroll-x>
							<!--  -->
							<view style="position: relative;" class="scrollx_items border "
								v-for="(item,index) in coverListData" :key="index" @click="coverSelected(item,index)">
								<!-- 遮罩层 -->
								<view class="coverMark" :class="{'coverActive':coverIndex==index}"></view>
								<view class="editDelete">
									<!-- 删除 -->
									<image style="width: 50rpx;height: 60rpx;" src="../../static/Shan2.png" mode=""
										@click.stop="removeFav(item,index)"></image>
									<!-- 编辑 -->
									<image style="width: 60rpx;height: 60rpx;" src="../../static/Btn-tu/Bian.png"
										mode="" @click.stop="editFav(item,index)"></image>
								</view>
								<image :src="item.thumb" mode="aspectFit" style="width: 100%;height: 100%;"></image>
							</view>
						</scroll-view>
					</view>
					<view class="scrollx_items borderDoted"
						style="margin-right: 20rpx;height: 420rpx;margin-left: 25rpx;margin-top: 5rpx;"
						@click.stop="coverTmeplateClick">
						<view
							style="width: 270rpx;height: 100%;display: flex;justify-content: center;align-items: center;">
							<u-icon size="40" name="plus" color="#D9D9D9"></u-icon>
						</view>
					</view>
				</view>


				<text class="title" style=" margin-top: 80rpx;font-size: 13px">内容模版</text>
				<!-- 添加区域 -->
				<view class="bottom_scrollx" style="">
					<u-scroll-list style="padding-left: 20rpx;padding-right: 20rpx;">
						<!--   -->
						<view class="borderImage" style="" @click="contentSelected(contentListData[0], 0)">
							<!-- 遮罩层 -->
							<view class="contentMark" :class="{'borderActive':contentIndex==0}"></view>
							<image style="" src="/static/template/content1.png" style="width: 280rpx;height: 100%;"
								mode="aspectFit">
							</image>
						</view>
						<view class="borderImage" style="" @click="contentSelected(contentListData[1], 1)">
							<!-- 遮罩层 -->
							<view class="contentMark" :class="{'borderActive':contentIndex==1}"></view>
							<image style="" src="/static/template/content2.png" style="width: 280rpx;height: 100%;"
								mode="aspectFit">
							</image>
						</view>
						<view class="firstChildImage " style="" @click="contentSelected(contentListData[2], 2)">
							<view class="borderImage" style="width: 420rpx;height: 280rpx">
								<!-- 遮罩层 -->
								<view class="contentMarkLast" :class="{'borderActive':contentIndex==2}"></view>
								<image style="" src="/static/template/content3.png" style="width: 100%;height: 100%;"
									mode="aspectFit">
								</image>
							</view>
						</view>
					</u-scroll-list>
				</view>


			</view>
			<!-- 底部浮动导航栏 -->
			<uni-fab ref="fab" :pattern="pattern" :content="fabList" horizontal="right" vertical="bottom"
				direction="horizontal" @trigger="trigger" />

			<uni-popup ref="PDFTemplate" type="dialog">
				<uni-popup-dialog ref="inputClose" @confirm="PDFResultConfirm('PDFTemplate')"
					@close="PDFResultClose('PDFTemplate')" :buttonType="'模版'" :cancelText="cancelText"
					:confirmText="confirmText">
					<template>
						<view>
							<view>PDF已生成,请选择下载或分享</view>
							<view class="">注:获得编辑版本请登录zytsaas.com</view>
						</view>
					</template>
				</uni-popup-dialog>
			</uni-popup>
			<uni-popup ref="PDFResult" type="dialog">
				<uni-popup-dialog ref="inputClose" @confirm="PDFResultConfirm('PDFResult')"
					@close="PDFResultClose('PDFResult')">
					<template>
						<view>
							<view>确认生成这个PDF报告吗?</view>
						</view>
					</template>
				</uni-popup-dialog>
			</uni-popup>
			<uni-popup ref="PDFResultDelete" type="dialog">
				<uni-popup-dialog ref="inputClose" @confirm="PDFResultConfirm('PDFResultDelete')"
					@close="PDFResultClose('PDFResultDelete')">
					<template>
						<view>
							<view>确认删除这个封皮模版吗?</view>
						</view>
					</template>
				</uni-popup-dialog>
			</uni-popup>

		</u-popup>
	</view>
</template>

<script>
	// 引入工具数据
	import {
		coverImageListData
	} from '@/utils/mock.js'
	import {
		getNowDate
	} from '@/utils/tools.js'
	import templateVue from './template.vue'
	export default {
		props: {
			show: {
				type: Boolean,
				default: false
			},
			parentObj: {
				type: Object,
				default: () => {}
			},
			data: {
				type: Object,
				default: () => {}

			}
		},
		data() {
			return {
				popupType: "",
				cancelText: "",
				confirmText: "",
				modalShow: false,
				content: '东临碣石，以观沧海',
				coverIndex: 0,
				contentIndex: 0,
				coverImageListData: coverImageListData,
				// 内容模版列表数据
				contentListData: [],
				// 封皮模版
				coverListData: [{
						thumb: "/static/template/cover1.png"
					},
					{
						thumb: "/static/template/cover2.png"
					}
				],
				flag: false,
				startX: 0,
				endX: 0,
				slideStyle: {
					left: 0,
					transition: 'none'
				},


				favId: '',
				favList: [], //收藏的列表数据
				fabList: [{
						iconPath: '/static/fixbtn/PDFPreView-off.png',
						selectedIconPath: '/static/fixbtn/PDFPreView.png',
						text: '预览',
						active: true
					},
					{
						iconPath: '/static/fixbtn/yes-off.png',
						selectedIconPath: '/static/fixbtn/yes.png',
						text: '完成',
						active: false
					}
				],
				pattern: {
					buttonColor: '#d1100b',
					selectedColor: '#d1100b',
					icon: 'more-filled',
					iconShow: 'more'
				},
				// 传递过来的项目id
				ProjectId: "",
				ReportName: "", //传递过来的报告名称  赋值添加的报告名称
				downloadUrl: "",
				coverRow: {} //要删除的当前行封皮模版数据
			}
		},
		// watch: {
		// 	favId: {
		// 		handler(n, o) {
		// 			if (n) {
		// 				// this.fabList[0].active = true
		// 				// this.fabList[0].text = '取消收藏'
		// 			} else {
		// 				// this.fabList[0].active = false
		// 				// this.fabList[0].text = '收藏'
		// 			}
		// 		}
		// 	}
		// },
		methods: {
			// 点击页面任意一点关闭三个点弹窗
			fabCloseClick() {
				// 默认关闭浮动按钮弹出菜单
				this.$nextTick(function() {
					this.$refs.fab.popMenu = true
					this.$refs.fab.isShow = false
				})
			},
			// 顶部封皮模版区域点击
			coverSelected(item, index) {
				console.log('选中的封皮模版是。', item)
				this.coverIndex = index
			},
			// 内容模版区域点击
			contentSelected(item, index) {
				this.contentIndex = index
				console.log('内容模版点击', item, this.contentIndex)
			},
			// 封皮模板添加
			coverTmeplateClick() {
				console.log('封皮模版添加', )
				// 默认关闭浮动按钮弹出菜单
				this.$nextTick(function() {
					this.$refs.fab.popMenu = true
					this.$refs.fab.isShow = false
				})
				console.log(this.data);
				uni.navigateTo({
					url: '/pages/report/template?ProjectId=' + this.ProjectId + '&type=新增' + '&ReportName=' + this
						.ReportName
				})
			},

			init(ProjectId) {
				this.show = true
				// this.favIndex = null
				// this.current = null
				// this.favId = ''
				// this.List = []
				// this.favList = []
				// this.detailList = []
				// this.show = true
				// 获取封皮模版和内容模版列表数据
				// this.getDataList()
				// this.getFavList(ProjectId)
			},
			// 关闭弹窗
			close() {
				this.$emit('close')
			},
			// 打开弹窗
			open() {
				this.$emit('open')
				// this.ProjectId = ProjectId
				// console.log('获取传递过来的项目id', this.ProjectId)
				// this.init()
			},
			// 按钮
			trigger(e) {
				if (e.index == 0) { //预览
					// 判斷是否有封皮模板
					if (this.coverListData.length == 0) return uni.showToast({
						title: '请先添加封皮模版',
						icon: "none"
					})

					this.fabList[0].active = true //预览亮起
					let data = uni.getStorageSync('previewData')
					let coverImageList = JSON.parse(this.coverListData[this.coverIndex].Detailed)
					data.template = coverImageList
					console.log('预览了-------------------', this.contentIndex, coverImageList, data)
					// let coverImageObj={}
					//  coverImageList.forEach(item=>{
					// 	if(item.ControlKey==='CompanyLogo') coverImageObj.coverLoGo = item.ControlValue
					// 	if(item.ControlKey==='ProjectImg') coverImageObj.ProjectImg = item.ControlValue
					// })
					uni.setStorageSync('previewData', data)
					let obj = {
						contentIndex: this.contentIndex, //选择的是哪一个模版匹配不同的模版布局
						data: this.parentObj.data,
						coverImageList: coverImageList
					}
					if (this.contentIndex == 0) { //内容模版1
						uni.navigateTo({
							url: '/pages/report/reportPreview?obj=' + encodeURIComponent(JSON.stringify(obj))
						})
					} else if (this.contentIndex == 1) { //内容模版2
						uni.navigateTo({
							url: '/pages/report/reportPreview2?obj=' + encodeURIComponent(JSON.stringify(obj))
						})
					} else { //内容模版3
						uni.navigateTo({
							url: '/pages/report/reportPreview3?obj=' + encodeURIComponent(JSON.stringify(obj))
						})
					}

				} else {
					console.log('打印111--', this.coverListData, this.contentListData, this.coverIndex, this.contentIndex)
					// 判斷是否有封皮模板 
					if (this.coverListData.length == 0) return uni.showToast({
						title: '请先添加封皮模版',
						icon: "none"
					})
					this.submitReportPDF()
				}
				// else if (e.index == 2) {
				// 	this.detailList.forEach(item => item.ControlValue = '')
				// } else if (e.index == 3) {
				// 	this.$emit('templateData', [...this.detailList])
				// 	this.$refs.template.close()
				// }
			},
			// 生成PDF
			submitReportPDF(obj) {
				this.popupType = "生成"
				this.fabList[1].active = true //完成亮起
				this.$refs.PDFResult.open() //弹窗确认
			},

			// 生成报告程工后弹窗提示确定下载
			PDFResultConfirm(type) {

				var that = this
				let obj = {
					ProjectId: this.parentObj.data.ProjectId, //项目id
					TaskId: this.parentObj.data.TaskId, //任务id
					ReportName: this.parentObj.data.ReportName, //报告名称
					EchartsImg: this.parentObj.base64List, //echarts图标数据
					CoverTemplateId: this.coverListData[this.coverIndex].Id, //封皮模版Id
					ContentTemplateId: this.contentListData[this.contentIndex].Id //内容模版Id
				}

				// 判断公共上传的项目任务参数条件和父组件中当前生成报告的项目任务参数条件是否相同  如果不是相同的，
				// 说明当前生成报告的不是最新上传好的 无需清空缓存entityProjectXmRwIdObj 如果相等  说明当前要生成的报告就是缓存中存储的项目任务下的报告  需要清空缓存
				if (uni.getStorageSync('entityProjectXmRwIdObj')) {
					console.log('开始走生成报告了有缓存entityProjectXmRwIdObj', type, this.parentObj, uni.getStorageSync(
						'entityProjectXmRwIdObj'))
					let entityProjectXmRwIdObj = uni.getStorageSync('entityProjectXmRwIdObj')
					if (entityProjectXmRwIdObj.xmId === this.parentObj.ReportObj.ProjectId && entityProjectXmRwIdObj
						.rwId === this
						.parentObj.ReportObj.Id) { //说明当前生成报告的是当前刚刚上传好的项目任务 清空缓存
						console.log('id相等可以移除')
						uni.removeStorageSync('entityProjectXmRwIdObj')
					} else {
						console.log('id不相等，可以不用移除')
					}

					console.log('获取是否移出entityProjectXmRwIdObj', uni.getStorageSync('entityProjectXmRwIdObj'))
				}

				if (type === 'PDFTemplate') { //走下载模版
					this.download(this.downloadUrl)
				} else if (type === 'PDFResult') { //走生成报告

					// 执行确认后的操作
					uni.showLoading({
						title: 'PDF生成中',
						mask: true
					})
					// 关闭浮动按钮弹出菜单 置灰完成按钮
					this.fabList[0].active = false
					this.fabList[1].active = false
					this.$nextTick(function() {
						console.log('获取是否展开菜单了', this.$refs.fab.popMenu, this.$refs.fab.isShow)
						this.$refs.fab.popMenu = true
						this.$refs.fab.isShow = false
					})
					that.$http('Base_ProjectWork/Base_Project/GetReportPDF', obj).then(res => {
						console.log('是否生成报告程工', res);
						uni.hideLoading()
						if (res.Success) {
							this.popupType = "下载分享"
							this.cancelText = "分享"
							this.confirmText = "下载"
							this.$refs.PDFTemplate.open() //弹窗下载pdf
							this.downloadUrl = res.Data //赋值下载PDF报告路径
							// that.download(res.Data)
						} else {
							uni.showToast({
								icon: 'none',
								title: res.Msg
							})
							that.parentObj.close()
						}
					})
				} else { //走删除
					uni.showLoading({
						title: '删除中'
					})
					// 暂时不打开待后续更改
					this.$http('Base_Template/Base_TemplateCollect/CancelFavoriteData', this.coverRow).then(
						res => {
							if (res.Success) {
								uni.showToast({
									icon: 'none',
									title: '已删除'
								})
								this.favId = ''
								this.favIndex = null
								// this.fabList[0].active = false
								// this.fabList[0].text = '收藏'
								setTimeout(function() {
									uni.hideLoading()
								}, 1500)
								// 刷新列表
								this.getFavList()
							} else uni.showToast({
								icon: 'none',
								title: res.Msg
							})

						})
				}


			},
			PDFResultClose(type) {
				if (type === 'PDFTemplate') { //只有生成模版后  点击取消才是分享按钮
					this.share(this.downloadUrl)
				}

			},
			// 下载模版
			download(url) {
				this.parentObj.close() //关闭选择模版页面  
				uni.showLoading({
					title: 'PDF下载中',
					mask: true
				})
				uni.downloadFile({
					url,
					header: {
						'Access-Control-Allow-Origin': '*'
					},
					filePath: '/Download',
					success: (res) => {
						console.log(res);
						uni.openDocument({
							filePath: res.tempFilePath,
							success: function(res) {
								console.log('打开文档成功');

							},
							fail: function(res) {
								uni.showToast({
									title: JSON.stringify(res)
								})
							}
						})
					},
					fail: (err) => {
						uni.showToast({
							icon: 'none',
							title: 'PDF下载失败,请重新尝试'
						})
					},
					complete() {
						uni.hideLoading()
					}
				})
			},
			// 微信分享
			share(url) {
				if (this.cancelText === '分享') {
					uni.share({
						provider: "weixin",
						scene: "WXSceneSession",
						type: 0,
						href: url, // 分享跳转的链接
						title: "报告分享", // 分享标题
						summary: this.parentObj.data.ProjectName + "报告", // 分享内容文字
						imageUrl: "https://www.yoojet.com/wx.png", //分享封面图片
						success: function(res) {
							// 此处是调起微信分享成功的回调
						},
						fail: function(err) {
							// 此处是调起微信分享失败的回调
							console.log(err);
						}
					});
				}

			},
			// 选择收藏
			favChange(e) {
				console.log(e);
				if (!e) {
					this.favIndex = null
					this.detailListGetData()
				} else {
					// 通过收藏Id获取对应下标后赋值新模板
					this.favIndex = this.favList.findIndex(item => item.Id == e)
					this.detailList = JSON.parse(this.favList[this.favIndex].Detailed)
					// 通过收藏下标获取赋值模板选中状态
					this.current = this.List.findIndex(item => item.Id == this.favList[this.favIndex].TempId)
				}
			},
			// 保存收藏
			dialogConfirm(e) {
				if (!e) return uni.showToast({
					icon: 'none',
					title: '请输入模板名称'
				})
				this.$http('Base_Template/Base_TemplateCollect/SaveTemplateCollectData', {
					"UserId": uni.getStorageSync('userInfo').Id,
					"Name": e,
					"TempId": this.List[this.current].Id,
					"Detailed": JSON.stringify(this.detailList),
					// 项目id
					ProjectId: this.ProjectId,
				}).then(res => {
					if (res.Success) {
						this.getFavList(true)
						this.fabList[0].active = true
						this.fabList[0].text = '取消收藏'
						uni.showToast({
							icon: 'none',
							title: '操作成功'
						})
					} else uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				})
			},
			// 编辑顶部封皮模版  也就是选来选中好的收藏下拉数据回显
			editFav(item, index) {
				console.log('编辑了', item, index)
				this.coverIndex = index
				let obj = JSON.stringify(item)
				uni.navigateTo({
					url: '/pages/report/template?ProjectId=' + item.ProjectId + '&Id=' + item.Id + '&type=编辑' +
						'&item=' + obj + '&ReportName=' + this
						.ReportName
				})
			},
			// 删除顶部封皮模版  也就是原来的取消收藏
			removeFav(item, index) {
				this.popupType = "删除"
				this.coverIndex = index
				this.coverRow = item
				console.log('取消收藏了-----', item, JSON.parse(item.Detailed), index, this.coverListData)
				this.$refs.PDFResultDelete.open()
			},
			// 模板选择
			selectTemplate(index) {
				this.coverIndex = index
				// if (index == this.current) return
				this.favId = ''
				// this.current = index
				this.detailListGetData()
			},
			detailListGetData() {
				this.detailList = JSON.parse(this.List[this.current].Detailed).sort((a, b) => a.Sort - b.Sort)
				console.log(getNowDate());
				this.detailList.forEach(item => {
					if (item.ControlType == 'Date') item.ControlValue = getNowDate()
					else if (item.ControlKey == 'ReportName') item.ControlValue = this.reportName

				})
			},
			// 获取顶部收藏的封皮模版列表数据 也就是原来的下拉收藏列表数据
			getFavList(fav) {
				this.$http('Base_Template/Base_TemplateCollect/GetTemplateCollectList?ProjectId=' + this.ProjectId, {
					SortField: "CreateTime",
					SortType: "desc",
				}).then(res => {
					if (res.Success) {
						this.coverListData = res.Data.map((item, index) => {
							return {
								...item,
								text: item.Name,
								value: item.Id,
								thumb: this.coverImageListData[index].thumb
							}
						})
						this.favList = this.coverListData
						if (fav) {
							this.favId = this.favList[0].value
							this.favIndex = 0
						}
					} else uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				})
			},
			// 获取封皮模版和内容模版相关数据
			getDataList() {
				this.$http('Base_Template/Base_PDFTemplate/GetPDFTemplateList').then(res => {
					if (res.Success) {
						this.List = res.Data
						let coverListData = this.List[0] //封皮模版
						let contentListData = [this.List[1], this.List[2], this.List[3]]
						// let newCoverListData = JSON.parse(coverListData.Detailed)
						this.contentListData = contentListData //内容模版数据赋值

						console.log('	// 获取封皮模版和内容模版相关数据', this.contentListData)
						if (this.List.length > 0) {
							this.current = 0
							this.detailListGetData()
						}
					}
				})
			},
			// 上传照片
			uploadImg(item) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (result) => {
						console.log(result);
						uni.showLoading({
							mask: true
						})
						uni.uploadFile({
							url: this.$url + 'Base_Manage/Upload/ProjectImgOssUploadFileByForm',
							filePath: result.tempFilePaths[0],
							name: 'file',
							header: {
								Authorization: uni.getStorageSync('tokenKey')
							},
							success: (res) => {
								console.log(res);
								if (!JSON.parse(res.data).Url) uni.showToast({
									icon: 'none',
									title: '上传失败!图片名称过长,请缩短名称后重新尝试'
								})
								item.ControlValue = JSON.parse(res.data).Url
							},
							fail: (err) => {
								console.log(err);
								uni.showToast({
									title: '网络连接失败,请重新尝试',
									icon: 'none'
								})
							},
							complete: (val) => {
								console.log();
								uni.hideLoading()
							}
						});
					},
					fail: () => {
						// uni.showToast({
						// 	title: '网络连接失败,请重新尝试',
						// 	icon: 'none'
						// })
					}
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	// 覆盖uview的u-popup的样式
	::v-deep.u-popup {
		.u-slide-left-enter-to {
			right: 0;
		}
	}

	.coverActive {
		border: 2px solid #D1100B !important;
		background-color: rgba(0, 0, 0, 0) !important;
	}

	.container {
		.scrollContent {
			.title {
				margin: 20rpx;
				// font-size: 20rpx;
				display: block;
			}

			.border {}

			.borderDoted {
				border: 2px dotted #AEB5C0;
			}

			.borderActive {
				border: 2px solid #D1100B !important;
				background-color: rgba(0, 0, 0, 0) !important;
			}

			.borderImage {
				height: 420rpx;
				margin-right: 30rpx;
			}

			.scrollx_items.open {
				width: 280rpx;
				height: 420rpx;
				margin-left: 20rpx;
				margin-right: 20rpx;
			}

			.top_scrollx,
			.bottom_scrollx {
				.contentMark {
					border: 2px solid #677490;
					background-color: rgba(106, 108, 113, 0.4);
					height: 100%;
					position: absolute;
					z-index: 99;
					width: 280rpx
				}

				.contentMarkLast {
					border: 2px solid #677490;
					background-color: rgba(106, 108, 113, 0.4);
					position: absolute;
					z-index: 99;
					width: 430rpx;
					height: 280rpx
				}

				.editDelete {
					position: absolute;
					z-index: 9999;
					height: 100%;
					right: 0;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					padding: 3px;
				}

				// justify-content: space-between;
				// align-items: center;
				.firstChildImage {
					display: flex;
					align-items: center;
					margin-right: 30rpx;
				}

				.scrollx_items {
					height: 420rpx;

					.coverMark {
						background-color: rgba(106, 108, 113, 0.4);
						width: 100%;
						height: 100%;
						position: absolute;
						z-index: 99;
						// border: 2px solid #959DAA;
						border: 2px solid #677490;
					}
				}



				.uni-swiper-tab {
					white-space: nowrap;

					.scrollx_items {
						width: 280rpx;
						height: 420rpx;
					}

					.bottom-scrollx_items {
						width: 360rpx;
						height: 420rpx;
					}

					.bottom-scrollx_items-row {
						width: 480rpx;
						height: 300rpx;

					}

					.scrollx_items,
					.bottom-scrollx_items,
					.bottom-scrollx_items-row {
						text-align: center;
						display: inline-block;
						box-sizing: border-box;
						margin-left: 30rpx;
						margin-top: 3px;
					}

					.scrollx_items:last-child {
						margin-right: 30rpx;
					}

					.scrollx_items image,
					.bottom-scrollx_items image {
						// width: 1005
						// height: 66rpx;
					}
				}
			}

		}






	}
</style>